package cn.lanchengkeji.datafillingsystem.controller;


import cn.lanchengkeji.datafillingsystem.common.Const;
import cn.lanchengkeji.datafillingsystem.common.ResponseBean;
import cn.lanchengkeji.datafillingsystem.common.StatusCode;
import cn.lanchengkeji.datafillingsystem.entity.OperationLog;
import cn.lanchengkeji.datafillingsystem.entity.Users;
import cn.lanchengkeji.datafillingsystem.exception.LoginException;
import cn.lanchengkeji.datafillingsystem.jwt.JWTUtil;
import cn.lanchengkeji.datafillingsystem.service.IOperationLogService;
import cn.lanchengkeji.datafillingsystem.service.IUsersService;
import cn.lanchengkeji.datafillingsystem.utils.HttpUtils;
import cn.lanchengkeji.datafillingsystem.utils.MD5Utils;
import cn.lanchengkeji.datafillingsystem.vo.UsersVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@Api(hidden = false, tags = {"登录 前端控制器"})
public class LoginController {
    @Resource
    private IUsersService usersService;

    @Resource
    private IOperationLogService iOperationLogService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseBean login(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              @RequestParam("verification") String verification,
                              @RequestParam("newVerification") String newVerification) {
        //验证验证码
        if (!(verification.trim().toLowerCase().equals(newVerification.trim().toLowerCase()))) {
            return new ResponseBean(StatusCode.V_ERR, null);
        }

        Users userBean = usersService.getUserByName(username);
        if (userBean == null) {
            return new ResponseBean(StatusCode.USER_NOT_FOUND, null);
        }

        if (userBean.getCheckFlag() == Const.USER_INFO_INCOMEPLETE_1) { //未补全信息
            return new ResponseBean(StatusCode.USER_INFO_INCOMEPLETE, null);

        } else if (userBean.getCheckFlag() == Const.USER_NOT_CHECK_2) { // 未审核
            return new ResponseBean(StatusCode.USER_NOT_CHECK, null);

        } else if (userBean.getCheckFlag() == Const.USER_CHECK_NOT_PASS_4) { //未通过
            return new ResponseBean(StatusCode.USER_CHECK_NOT_PASS, null);
        }

        if (userBean.getPasswd().equals(password)) {
            if (userBean.getDelFlag().equals(0)) {
                return new ResponseBean(HttpStatus.OK, HttpStatus.OK.value(), "登录成功", JWTUtil.sign(username, password));
            } else {
                return new ResponseBean(StatusCode.USER_DELETE, null);
            }

        } else {
            throw new LoginException();
        }

    }


    @RequestMapping(value = "/admin-login", method = RequestMethod.POST)
    public ResponseBean adminLogin(HttpServletRequest request,
                                   @RequestParam("username") String username,
                                   @RequestParam("password") String password,
                                   @RequestParam("verification") String verification,
                                   @RequestParam("newVerification") String newVerification) {
        //验证验证码
        if (!(verification.trim().toLowerCase().equals(newVerification.trim().toLowerCase()))) {
            return new ResponseBean(StatusCode.V_ERR, null);
        }

        UsersVO condition = new UsersVO();
        condition.setUserName(username);
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(condition);
        Users userBean = usersService.getOne(queryWrapper);

        if (userBean == null) {
            return new ResponseBean(StatusCode.USER_NOT_FOUND, null);
        }

        if (userBean.getCheckFlag() == Const.USER_INFO_INCOMEPLETE_1) { //未补全信息
            return new ResponseBean(StatusCode.USER_INFO_INCOMEPLETE, null);

        } else if (userBean.getCheckFlag() == Const.USER_NOT_CHECK_2) { // 未审核
            return new ResponseBean(StatusCode.USER_NOT_CHECK, null);

        } else if (userBean.getCheckFlag() == Const.USER_CHECK_NOT_PASS_4) { //未通过
            return new ResponseBean(StatusCode.USER_CHECK_NOT_PASS, null);
        }

        // 验证是否是管理端用户
        if (userBean.getUserType() != 1) {
            return new ResponseBean(StatusCode.USER_NOT_ADMIN, null);
        }

        if (userBean.getPasswd().equals(password)) {
            if (userBean.getDelFlag().equals(0)) {

                OperationLog operationLog = new OperationLog();
                operationLog.setOperationUserId(userBean.getId());
                operationLog.setOperationRealName(userBean.getRealName());
                operationLog.setOperationUserName(userBean.getUserName());
                operationLog.setOperationUserOrganization(userBean.getOrganization());
                operationLog.setOperationDate(new Date());
                operationLog.setRemoteIp(HttpUtils.getIPAddress(request));
                operationLog.setOperationType("登录");
                operationLog.setOperationEvent("登录");
                // 只有二级菜单下的操作才记录日志
                operationLog.setOperationMenu("系统登录");
                iOperationLogService.save(operationLog);

                return new ResponseBean(HttpStatus.OK, HttpStatus.OK.value(), "登录成功", JWTUtil.sign(username, password));
            } else {
                return new ResponseBean(StatusCode.USER_DELETE, null);
            }

        } else {
            throw new LoginException();
        }

    }

    @RequestMapping(value = "/401")
    public ResponseBean exception401() {
        throw new AuthenticationException();
//        return new ResponseBean(HttpStatus.UNAUTHORIZED, 401, "Unauthorized", "");
    }

    @ApiOperation(hidden = false, value = "客户端注册", notes = "注册")
    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    public ResponseBean reg(@RequestBody UsersVO usersParam) {
        String verification = usersParam.getVerification();
        String newVerification = usersParam.getNewVerification();
        //验证验证码
        if (!(verification.trim().toLowerCase().equals(newVerification.trim().toLowerCase()))) {
            return new ResponseBean(StatusCode.V_ERR, null);
        }
        // 验证用户名是否存在
        boolean ret;
        synchronized (usersService) {
            Users user = usersService.getUserByName(usersParam.getUserName());
            if (user != null) {
                return new ResponseBean(StatusCode.USER_NAME_REPEAT, null);
            }

            UsersVO nUsers = new UsersVO();
            nUsers.setUserType(1);//服务端用户
            nUsers.setDelFlag(0);
            nUsers.setUserName(usersParam.getUserName());// 用户名
            nUsers.setPasswd(MD5Utils.getStringMD5(usersParam.getPasswd()));// 密码
            nUsers.setMail(usersParam.getMail());
            nUsers.setCreateTime(new Date());
            // 未审核
            nUsers.setCheckFlag(Const.USER_INFO_INCOMEPLETE_1); //未补全信息
            ret = usersService.save(nUsers);
        }
        if (!ret) {
            return new ResponseBean(StatusCode.USER_REG_FAIL, null);
        }
        return new ResponseBean(StatusCode.OK, null);
    }
}